
var websocket = null;
export function init(wsUrl) {

	return new Promise(function (resolve, reject) {
		//判断当前浏览器是否支持WebSocket，是则创建WebSocket
		if ('WebSocket' in window) {
			console.log("浏览器支持Websocket");
			websocket = new WebSocket(wsUrl);
		} else {
			alert('当前浏览器 Not support websocket')
		}

		//连接发生错误的回调方法
		websocket.onerror = function () {
			console.log("WebSocket连接发生错误");
		};
		//连接成功建立的回调方法
		websocket.onopen = function () {
			console.log("WebSocket连接成功");
		}
		//接收到消息的回调方法
		websocket.onmessage = function (event) {
			console.log(event.data);
			resolve(event.data)
		}
		//连接关闭的回调方法
		websocket.onclose = function () {
			console.log("WebSocket连接关闭");
		}

		openWebSocket(wsUrl)
	})

}

//关闭WebSocket连接
export function closeWebSocket() {
	websocket.close();
}

// // //发送消息
// export function send(message) {
// 	console.log(message);
// 	console.log(websocket);
// 	websocket.send(message);
// }


// 建立连接的方法
function openWebSocket(wsUrl) {
	websocket = new WebSocket(wsUrl);
	websocket.onopen = function () {
		console.log("WebSocket连接成功");
	}
}

//如果websocket连接还没断开就关闭了窗口，后台server端会抛异常。
//所以增加监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接
window.onbeforeunload = function () {
	closeWebSocket();
}
export default {
	websocket
}